import msg from "../model/msg";

let socketOpen: boolean = false; // socket连接指示
let socketClose: boolean = false; // socket是否已经调用关闭的方法
let id_flag = wx.getStorageSync('id_flag'); // 登录用户的身份
let isFirst: boolean;
let heart: boolean = false; // 判断心跳变量
let heartBeatFailCount: number = 0; // 心跳失败次数
let heartBeatTimeOut: number | null = null; // 心跳超时计时器
let connectSocketTimeOut: number | null = null; // 连接超时计时器

/**
 * @interface 发送websocket的传入数据范式
 */
interface SendData {
  type: string;
}
/**
 * @module WebSocket
 */
export const webSocket =  {
  /**
   * @function 创建一个WebSocket连接
   */
  connectSocket: function() {
    socketOpen = false;
    socketClose = false;
    isFirst = true;
    wx.connectSocket({
      url: 'wss://sanli-tracks.com/wss',
      success: res => {
        console.log('WebSocket 连接成功', res);
      },
      fail: err => {
        console.error('WebSocket 连接失败', err);
      }
    })
  },
  /**
   * @function 通过WebSocket连接发送数据
   * @param data 需要发送的内容
   */
  sendSocketMessage: function(data: SendData) {
    const type = data.type;
    if(socketOpen) {
      const DATA = JSON.stringify(data);
      console.log('WebSocket输出数据', DATA);
      wx.sendSocketMessage({
        data: DATA,
        success: res => {
          console.log('WebSocket输出成功', res);
        },
        fail: err => {
          if(type == 'getgps') {
            msg.Fail('定位获取失败');
          }
          console.error('WebSocket输出失败', err);
        }
      })
    } // if(socketOpen)
    else {
      console.error('发送消息失败，WebSocket已关闭');
    }
  },
  /**
   * @function 关闭WebSocket连接
   */
  closeSocket: function() {
    if(connectSocketTimeOut) {
      clearTimeout(connectSocketTimeOut);
      connectSocketTimeOut = null;
    }
    socketClose = true;
    this.stopHeartBeat(); // 终止心跳
    wx.closeSocket({
      success: res => {
        console.log('WebSocket关闭成功');
      },
      fail: err => {
        console.error('WebSocket关闭失败');
      }
    })
  },
  /**
   * @function 消息回调
   * @param msg 消息
   */
  onSocketMessageBack: (msg: any) => {
    console.log('收到消息回调', msg)
  },
  /**
   * @function 开始心跳
   */
  startHeartBeat: function() {
    console.log('WebSocket开始心跳');
    heart = true;
    this.heartBeat(); // 心跳
  },
  /**
   * @function 结束心跳
   */
  stopHeartBeat: function() {
    console.log('WebSocket结束心跳');
    heart = false;
    if(heartBeatTimeOut) {
      clearTimeout(heartBeatTimeOut);
      heartBeatTimeOut = null;
    }
    if(connectSocketTimeOut) {
      clearTimeout(connectSocketTimeOut);
      connectSocketTimeOut = null;
    }
  },
  /**
   * @function 心跳
   */
  heartBeat: function() {
    if(!heart) {
      return;
    }
    let data = JSON.stringify({
      'type': 'heartbeat',
    })
    const that = this;
    wx.sendSocketMessage({
      data: data,
      success: (res) => {
        console.log('WebSocket心跳成功', res);
        if(heart) {
          if(heartBeatTimeOut) {
            clearTimeout(heartBeatTimeOut);
          }
          heartBeatTimeOut = setTimeout(() => {
            that.heartBeat();
          }, 60000);
        } // 是否在心跳
        heartBeatFailCount = 0; // 失败次数清零
      }, // success 回调
      fail: (err) => {
        console.log('WebSocket心跳失败');
        if(heartBeatFailCount > 2) {
          // 重连
          that.connectSocket();
        }
        if(heart) {
          if(heartBeatTimeOut) {
            clearTimeout(heartBeatTimeOut)
          }
          heartBeatTimeOut = setTimeout(() => {
            that.heartBeat();
          }, 60000)
        } // 是否心跳
        heartBeatFailCount ++; // 累计失败次数
      } // fail 回调
    }); // sendSocketMessage
  },

} // module end
/**
 * @function 监听WebSocket接收到服务器消息事件
 */
wx.onSocketMessage((res) => {
  console.log('WebSocket已打开!', res);
  if(socketClose) {
    webSocket.closeSocket();
    return;
  }
  socketOpen = true;
  let data: any = '';
  if(typeof res.data == 'string') {
    data = JSON.parse(res.data);
  }
  id_flag = wx.getStorageSync('id_flag'); // 获取用户身份
  if(isFirst && data.type == 'handshake') {
    // 获取当前位置信息
    
  }
})